import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  DrawerForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { Card, Col, Divider, Row } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';

import * as apiAreaFilter from '@/services/areaFilter';
import * as c from '@/services/consts';
import { EditableProTable, ProColumns } from '@ant-design/pro-table';

type FormProps = {
  visible: boolean;
  defaultProductId: number | undefined;
  current: API.Announce | undefined;
  onCancel: () => void;
  onSubmit: (values: API.Announce) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, defaultProductId, current, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  let defaultCurrent: Partial<API.Announce> | undefined = undefined;
  if (!current) {
    defaultCurrent = {
      productId: defaultProductId,
      closeable: true,
      sort: 1,
      status: true,
    };
  }

  let defaultPlatformAppVerCompareData: API.AppVerComparePolicy[] =
    current && current.policy?.platformAppVerCompares
      ? current.policy?.platformAppVerCompares
      : [];

  const [
    editablePlatformAppVerCompareKeys,
    setEditablePlatformAppVerCompareKeys,
  ] = useState<React.Key[]>(() =>
    defaultPlatformAppVerCompareData.map((item) => item.id),
  );
  const [platformAppVerCompareDataSource, setPlatformAppVerCompareDataSource] =
    useState<API.AppVerComparePolicy[]>(() => defaultPlatformAppVerCompareData);

  const formRef = useRef<ProFormInstance>();

  const { getProduct, getProductOptions } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductOptions: model.getProductOptions,
    }),
  );

  const productOptions = getProductOptions(false);

  const loadAreaFilters = async (params: { [key: string]: any }) => {
    const result = await apiAreaFilter.all(params);

    if (result.success && result.data && result.data.length > 0) {
      let options: any[] = [];
      for (let item of result.data) {
        let product = getProduct(item.productId);
        let areas =
          item.areaGroup == c.AreaGroup.Foreign.value
            ? item.areas
            : item.areaGroup;

        options.push({
          label: `(${product?.name})${item.name} [${areas}]`,
          value: item.id,
          disabled: !item.status,
        });
      }

      return Promise.resolve(options);
    }

    return Promise.resolve([]);
  };

  const handleFormSubmit = async (record: API.Announce) => {
    if (!record.policy) {
      record.policy = {} as API.AnnouncePolicy;
    }
    record.policy.platformAppVerCompares = platformAppVerCompareDataSource;

    onSubmit(record);
  };

  const platformAppVerCompareColumns: ProColumns<API.AppVerComparePolicy>[] = [
    {
      title: '平台',
      dataIndex: 'platform',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.PlatformOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择平台' }],
        };
      },
    },
    {
      title: '比较方式',
      dataIndex: 'compareMode',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.AdPolicyAppVerCompareOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择比较方式' }],
        };
      },
    },
    {
      title: '版本号',
      width: 80,
      dataIndex: 'appVer',
      valueType: 'digit',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请填写版本号比较方式' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];

  return (
    <DrawerForm<API.Announce>
      open={visible}
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      title={`${current ? '编辑' : '添加'}公告`}
      initialValues={current ? current : defaultCurrent}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <Row gutter={24}>
        <Col span={24}>
          <ProFormSelect
            name="productId"
            label="产品"
            options={productOptions}
            rules={[{ required: true, message: '请选择产品' }]}
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={24}>
          <ProFormText
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
            placeholder="请输入标题"
          />
        </Col>
        <Col span={24}>
          <ProFormText name="linkUrl" label="链接" />
        </Col>
        <Col span={24}>
          <ProFormTextArea
            name="content"
            label="内容"
            fieldProps={{ rows: 6 }}
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormDigit
            name="sort"
            label="排序"
            wrapperCol={{ span: 4 }}
            min={0}
            max={9999}
            fieldProps={{ defaultValue: 0 }}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <ProFormSwitch name="closeable" label="允许关闭" />
        </Col>
        <Col span={12}>
          <ProFormSwitch name="reminderInterval" label="间隔提醒" />
        </Col>
        <Col span={12}>
          <ProFormDependency name={['reminderInterval']}>
            {({ reminderInterval }) => {
              if (reminderInterval === true) {
                return (
                  <ProFormDigit
                    name="reminderIntervalTimes"
                    label="间隔时间(小时)"
                    min={1}
                    max={720}
                    rules={[
                      { required: true, message: '请输入间隔时间(小时)' },
                    ]}
                    placeholder="请输入间隔时间(小时)"
                  />
                );
              }
              return null;
            }}
          </ProFormDependency>
        </Col>
        <Col span={12}>
          <ProFormSwitch name="status" label="状态" />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={24}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
      </Row>
      <Card title="显示策略" style={{ margin: 0, padding: 0 }}>
        <Row gutter={24}>
          <Col span={24}>
            <ProFormCheckbox.Group
              name="memberLevels"
              label="用户等级"
              options={c.MemberLevelOptions}
              rules={[{ required: true, message: '请选择用户等级' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormCheckbox.Group
              name="platforms"
              label="平台"
              options={c.PlatformOptions}
              rules={[{ required: true, message: '请选择平台' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormCheckbox.Group
              name="channels"
              label="渠道"
              options={c.Channels}
              rules={[{ required: true, message: '请选择渠道' }]}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              版本策略
            </Divider>
          </Col>
          {/* <Col span={12}>
            <ProFormSelect
              name={['policy', 'appVerCompare']}
              label="版本比较"
              options={c.AdPolicyAppVerCompareOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit name={['policy', 'appVer']} label="版本号" min={0} />
          </Col> */}
          <Col span={24}>
            <ProForm.Item name={['policy', 'platformAppVerCompares']} label="">
              <EditableProTable<API.AppVerComparePolicy>
                rowKey="id"
                locale={{ emptyText: '暂无数据' }}
                toolBarRender={false}
                columns={platformAppVerCompareColumns}
                defaultValue={platformAppVerCompareDataSource}
                // onChange={setPlatformAppVerCompareDataSource}
                onChange={(value: API.AppVerComparePolicy[]) => {
                  setPlatformAppVerCompareDataSource(value);
                }}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  position: 'bottom',
                  record: () => ({
                    id: `${Date.now()}`,
                    appVer: 0,
                  }),
                }}
                editable={{
                  type: 'multiple',
                  editableKeys: editablePlatformAppVerCompareKeys,
                  actionRender: (row, config, defaultDom) => [
                    //defaultDom.save,
                    defaultDom.delete,
                  ],
                  onValuesChange: (record, recordList) => {
                    setPlatformAppVerCompareDataSource(recordList);
                  },
                  onChange: setEditablePlatformAppVerCompareKeys,
                }}
                request={async () => ({
                  data: platformAppVerCompareDataSource,
                  success: true,
                })}
                // params={{ d: platformAppVerCompareDataSource }}
              />
            </ProForm.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              地区策略
            </Divider>
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayAreaFilterPolicy']}
              label="策略"
              options={c.GroupDisplayAreaFilterPolicyOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDependency name={['productId']}>
              {({ productId }) => {
                return (
                  <ProFormCheckbox.Group
                    name={['policy', 'displayAreaFilterPolicyAreaFilterIds']}
                    label="地区"
                    params={{ productIds: [productId] }}
                    request={loadAreaFilters}
                  />
                );
              }}
            </ProFormDependency>
          </Col>
        </Row>
      </Card>
    </DrawerForm>
  );
};

export default Form;
